<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + '建筑设施'"
    width="600px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <tdMap
      :isShowCreateDialog.sync="mapShow"
      :data="latlng"
      @close="close"
      @result="getLatlng"
    >
    </tdMap>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import {
  addFacilities,
  detail,
  editFacilities,
  getParkList,
  getBuildingList,
} from "@/api/basicdata/construction";
import tdMap from "@/components/netWorkmap/map";
import FormButton from "@/components/FormButton";
import { replaceDigit, dealElectricity, replaceInteger } from "@/utils/index";

export default {
  dicts: ["building_type", "house_structure"],
  components: { FormButton, tdMap },
  props: {
    id: { type: [Number, String], default: "" },
    visible: { type: Boolean, default: false },
  },
  data() {
    return {
      parkOptions: [],
      buildingOptions: [],
      latlng: {
        lat: null,
        lng: null,
      },
      mapShow: false,
      loading: false,
      apsForm: {
        formRef: "form",
        formData: {
          sort: 99, // 设置默认值
          status: true,
          custom: false, // 保持和registerForm一致
        },
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              name: [
                {
                  required: true,
                  message: "请输入建筑设施名称",
                  trigger: "blur",
                },
              ],
              direction: [
                {
                  required: true,
                  message: "请输入朝向",
                  trigger: "blur",
                },
              ],
              floor: [
                {
                  required: true,
                  message: "请输入楼层",
                  trigger: "blur",
                },
              ],
              latitude: [
                {
                  required: true,
                  message: "请输入或选择建筑设施经度",
                  trigger: ["blur", "change"],
                },
              ],
              longitude: [
                {
                  required: true,
                  message: "请输入或选择建筑设施纬度",
                  trigger: ["blur", "change"],
                },
              ],
              buildingType: [
                {
                  required: true,
                  message: "请选择建筑类型",
                  trigger: ["blur", "change"],
                },
              ],
              houseStructure: [
                {
                  required: true,
                  message: "请选择房屋结构",
                  trigger: ["blur", "change"],
                },
              ],
              parkId: [
                {
                  required: true,
                  message: "请选择园区",
                  trigger: ["blur", "change"],
                },
              ],
              buildingId: [
                {
                  required: true,
                  message: "请选择楼幢",
                  trigger: ["blur", "change"],
                },
              ],
              address: [
                {
                  required: true,
                  message: "请输入建筑设施地址",
                  trigger: "blur",
                },
              ],
              landArea: [
                { required: true, message: "请输入用地面积", trigger: "blur" },
              ],
              buildArea: [
                { required: true, message: "请输入建筑面积", trigger: "blur" },
              ],
              completionTime: [
                {
                  required: true,
                  message: "请选择竣工日期",
                  trigger: ["blur", "change"],
                },
              ],
            },
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            name: {
              typeName: "el-input",
              label: "建筑设施名称",
            },
            buildingType: {
              typeName: "el-select",
              label: "建筑类型",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.building_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "建筑类型",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "buildingType",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: parseInt(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            address: {
              typeName: "el-input",
              label: "建筑设施地址",
            },
            parkId: {
              typeName: "el-select",
              label: "园区",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.getBuilding(value);
                        },
                      },
                    },
                    [
                      that.parkOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              typeName: "el-select",
              label: "楼幢",
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择",
                        value: valNum,
                        disabled: !that.$refs?.form?.getFieldsValue().parkId,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                        },
                      },
                    },
                    [
                      that.buildingOptions.map((item) => {
                        let { id, name } = item;
                        return h("el-option", {
                          props: {
                            label: name,
                            value: id,
                            key: id,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floor: {
              typeName: "el-input",
              label: "楼层",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入楼层"
                      value={this.$refs?.form?.getFieldsValue().floor}
                      clearable
                      onInput={(value) => this.setVal(value, "floor")}
                    >
                      <template slot="append">层</template>
                    </el-input>
                  </div>
                );
              },
            },
            landArea: {
              label: "用地面积",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入用地面积"
                      value={this.$refs?.form?.getFieldsValue().landArea}
                      clearable
                      onInput={(value) => this.setVal(value, "landArea")}
                    >
                      <template slot="append">平方</template>
                    </el-input>
                  </div>
                );
              },
            },
            buildArea: {
              label: "建筑面积",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      placeholder="请输入建筑面积"
                      value={this.$refs?.form?.getFieldsValue().buildArea}
                      clearable
                      onInput={(value) => this.setVal(value, "buildArea")}
                    >
                      <template slot="append">平方</template>
                    </el-input>
                  </div>
                );
              },
            },
            houseStructure: {
              typeName: "el-select",
              label: "房屋结构",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.house_structure.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().houseStructure;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "房屋结构",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "houseStructure",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: parseInt(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            direction: {
              typeName: "el-input",
              label: "朝向",
            },
            completionTime: {
              typeName: "el-date-picker",
              type: "date",
              label: "竣工日期",
              "value-format": "yyyy-MM-dd",
              placeholder: "请选择竣工日期",
            },
            latitude: {
              typeName: "el-select",
              label: "经度",
              render: (h) => {
                return (
                  <div class="map">
                    <el-input
                      value={this.$refs?.form?.getFieldsValue().latitude}
                      placeholder="请输入或选择建筑设施经度"
                      maxlength={14}
                      clearable
                      onInput={(value) => this.setVal(value, "latitude")}
                    ></el-input>
                    <el-button onClick={this.openMap}>地图</el-button>
                  </div>
                );
              },
            },
            longitude: {
              typeName: "el-select",
              label: "纬度",
              render: (h) => {
                return (
                  <div>
                    <el-input
                      value={this.$refs?.form?.getFieldsValue().longitude}
                      placeholder="请输入或选择建筑设施纬度"
                      maxlength={14}
                      clearable
                      onInput={(value) => this.setVal(value, "longitude")}
                    ></el-input>
                  </div>
                );
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.getPark();
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    getInfo() {
      detail({ id: this.id })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          this.getBuilding(res.data.parkId);
          newData.landArea = dealElectricity(res?.data?.landArea);
          newData.buildArea = dealElectricity(res?.data?.buildArea);
          this.$refs?.form?.setFieldsValue(newData);
          this.latlng = {
            lat: newData.latitude,
            lng: newData.longitude,
          };
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!300404");
        });
    },
    getPark() {
      getParkList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.parkOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300406");
        });
    },
    getBuilding(val) {
      if (!val) return false;
      getBuildingList({ parkId: val })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.buildingOptions = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300407");
        });
    },
    getLatlng(e) {
      const { lat, lng } = e;
      this.$refs?.form?.setFieldValue("latitude", lat.toFixed(7));
      this.$refs?.form?.setFieldValue("longitude", lng.toFixed(7));
      this.latlng = {
        lat,
        lng,
      };
    },
    // 选择地图
    openMap() {
      this.mapShow = true;
    },
    close(status) {
      this.mapShow = false;
    },
    setVal(value, key) {
      if (key === "floor") {
        this.$refs?.form?.setFieldValue("floor", replaceInteger(value));
      } else if (key === "landArea" || key === "buildArea") {
        this.$refs?.form?.setFieldValue(key, replaceDigit(value, 2));
      } else {
        this.$refs?.form?.setFieldValue(key, value);
      }
    },

    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
        landArea: this.$refs.form.getFieldsValue().landArea * 100,
        buildArea: this.$refs.form.getFieldsValue().buildArea * 100,
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            editFacilities(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!300403");
              });
          } else {
            addFacilities(data)
              .then((res) => {
                this.loading = false;
                if (res.code === 700) {
                  this.$message.warning(res.msg);
                  return false;
                }
                this.$message.success("操作成功");
                this.handleClose(true);
              })
              .catch(() => {
                this.loading = false;
                // this.$message.error("系统错误,请联系管理员!300402");
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
